package com.vanrui.pcp.autocode.template;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import org.apache.log4j.Logger;

import com.vanrui.pcp.autocode.model.entry.ProjectClass;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Process {
	
	private final static Logger logger = Logger.getLogger(Process.class);
	
	private Environment evnm = null;
	
	private List<ProjectClass> projectClazzs = null;
	
	public Process(Environment evnm) throws Exception{
		this.evnm = evnm;
		init();
	}
	
	private void init() throws Exception{
		evnm.initEnvironment();
	}
	
	public Process(Environment evnm, List<ProjectClass> projectClazzs){
		this.evnm = evnm;
	}
	
	public int start() throws Exception{
		if(projectClazzs == null || projectClazzs.size() == 0){
			logger.error("没有需要生成的类");
			return 0;
		}
		return process();
	}

	private int process() throws Exception{
		int num = 0;
		Configuration cfg = evnm.getCfg();
		try {
			for (ProjectClass projectClazz : projectClazzs) {
				Template t = cfg.getTemplate(projectClazz.getTemplate(), "utf-8");
				logger.info("生成文件  "+projectClazz.getFileName()+"-->"+projectClazz.getFilePath());
				File file = new File(projectClazz.getFileDirectory());
				file.mkdirs();
				FileOutputStream fos = new FileOutputStream(projectClazz.getFilePath());//java文件的生成目录
				t.process(projectClazz.getClassData(), new OutputStreamWriter(fos,"utf-8"));//  
	            fos.flush();
	            fos.close();
	            num++;
			}
		} catch (IOException e) {
			throw new Exception(e);
		} catch (TemplateException e) {
			throw new Exception(e);
		}
		return num;
	}
	
	public List<ProjectClass> getProjectClazzs() {
		return projectClazzs;
	}

	public void setProjectClazzs(List<ProjectClass> projectClazzs) {
		this.projectClazzs = projectClazzs;
	}
}
